/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.promodel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.pro.entity.Pro;
import vip.xiaonuo.modular.pro.service.ProService;
import vip.xiaonuo.modular.promodel.entity.ProModel;
import vip.xiaonuo.modular.promodel.enums.ProModelExceptionEnum;
import vip.xiaonuo.modular.promodel.mapper.ProModelMapper;
import vip.xiaonuo.modular.promodel.param.ProModelParam;
import vip.xiaonuo.modular.promodel.result.ProModelResult;
import vip.xiaonuo.modular.promodel.service.ProModelService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.workorder.entity.WorkOrder;
import vip.xiaonuo.modular.workorder.service.WorkOrderService;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 产品型号表service接口实现类
 *
 * @author wz
 * @date 2022-05-25 10:08:07
 */
@Service
public class ProModelServiceImpl extends ServiceImpl<ProModelMapper, ProModel> implements ProModelService {



    @Resource
    private ProService proService;
    @Resource
    private WorkOrderService workOrderService;
    @Override
    public PageResult<ProModelResult> page(ProModelParam proModelParam) {
        QueryWrapper<ProModelResult> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(proModelParam)) {

            // 根据产品型号编码 查询
            if (ObjectUtil.isNotEmpty(proModelParam.getCode())) {
                queryWrapper.like("a.code", proModelParam.getCode());
            }
            // 根据产品型号名称 查询
            if (ObjectUtil.isNotEmpty(proModelParam.getName())) {
                queryWrapper.like("a.name", proModelParam.getName());
            }
            // 根据产品ID 查询
            if (ObjectUtil.isNotEmpty(proModelParam.getProId())) {
                queryWrapper.inSql("a.pro_id", proModelParam.getProId());
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(proModelParam.getRemarks())) {
                queryWrapper.like("a.remarks", proModelParam.getRemarks());
            }
        }
        return new PageResult<>(this.baseMapper.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<ProModel> list(ProModelParam proModelParam) {
        return this.list();
    }

    @Override
    public void add(ProModelParam proModelParam) {
        checkParam(proModelParam,false);
        ProModel proModel = new ProModel();
        BeanUtil.copyProperties(proModelParam, proModel);
        Pro pro = proService.getById(proModel.getProId());
        if(pro==null)
        {
            //找不到产品相应的产品类型，报异常
            throw new ServiceException(ProModelExceptionEnum.NOT_EXIST) ;
        }
        else{
            proModel.setProTypeId(pro.getProTypeId());
            this.save(proModel);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ProModelParam> proModelParamList) {
        DeleteVer(proModelParamList);
        proModelParamList.forEach(proModelParam -> {
            this.removeById(proModelParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ProModelParam proModelParam) {
        checkParam(proModelParam,true);
        ProModel proModel = this.queryProModel(proModelParam);
        BeanUtil.copyProperties(proModelParam, proModel);
        Pro pro = new Pro();
        pro=proService.getById(proModel.getProId());
        proModel.setProTypeId(pro.getProTypeId());
        this.updateById(proModel);
    }

    @Override
    public ProModel detail(ProModelParam proModelParam) {
        return this.queryProModel(proModelParam);
    }

    /**
     * 获取产品型号表
     *
     * @author wz
     * @date 2022-05-25 10:08:07
     */
    private ProModel queryProModel(ProModelParam proModelParam) {
        ProModel proModel = this.getById(proModelParam.getId());
        if (ObjectUtil.isNull(proModel)) {
            throw new ServiceException(ProModelExceptionEnum.NOT_EXIST);
        }
        return proModel;
    }

    @Override
    public void export(ProModelParam proModelParam) {
        List<ProModel> list = this.list(proModelParam);
        PoiUtil.exportExcelWithStream("SnowyProModel.xls", ProModel.class, list);
    }
    /**
     * 校验参数，检查是否存在相同的编码
     *
     * @author wz
     * @date 2022/5/27
     */
    private void checkParam(ProModelParam proModelParam,boolean isExcludeSelf) {
        LambdaQueryWrapper<ProModel> queryWrapperByCode = new LambdaQueryWrapper<>();
        String code = proModelParam.getCode();
        //编辑
        if (isExcludeSelf)
        {
            long id = proModelParam.getId();
            queryWrapperByCode.ne(ProModel::getId,id);
        }
        queryWrapperByCode.eq(ProModel::getCode, code);
        int countByCode = this.count(queryWrapperByCode);
        if (countByCode >= 1) {
            throw new ServiceException(ProModelExceptionEnum.ORG_CODE_REPEAT);
        }

        String name = proModelParam.getName();
        String proId = proModelParam.getProId();
        LambdaQueryWrapper<ProModel> queryWrapperByName = new LambdaQueryWrapper<>();
        if (isExcludeSelf)
        {
            long id = proModelParam.getId();
            queryWrapperByName.ne(ProModel::getId,id);
        }
        queryWrapperByName.eq(ProModel::getName,name);
        queryWrapperByName.eq(ProModel::getProId,proId);
        int countByName = this.count(queryWrapperByName);
        if (countByName >= 1) {
            throw new ServiceException(ProModelExceptionEnum.ORG_NAME_REPEAT);
        }
    }
    /**
     * 删除校验
     *
     * @author wz
     * @date 2022/5/30
     */
    private void DeleteVer(List<ProModelParam> proModelParamList){
        StringBuffer str = new StringBuffer() ;
        str.append("工单管理存在型号名称为");
        AtomicInteger count = new AtomicInteger();
        proModelParamList.forEach(proModelParam -> {
            LambdaQueryWrapper<WorkOrder> queryWrapperById= new LambdaQueryWrapper<>();
            queryWrapperById.eq(WorkOrder::getProModelId,proModelParam.getId());
            int countByCode = workOrderService.count(queryWrapperById);
            if (countByCode>=1){
                ProModel proModel = this.getById(proModelParam.getId());
                count.getAndIncrement();
                str.append(proModel.getName()+"、");
            }
        });
        if (count.decrementAndGet()>=0)
        {
            str.append("请先删除相应的工单");
            throw new ServiceException(4,str.toString());
        }
    }

}
